package com.five.system.service.impl;

import com.five.basic.result.PageList;
import com.five.basic.service.impl.BaseServiceImpl;
import com.five.pojo.Menu;
import com.five.system.mapper.MenuMapper;
import com.five.system.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public PageList<Menu> queryPage(Menu menu) {
        Integer total = menuMapper.queryCount(menu);
        if (total == 0) {
            return new PageList<>();
        }
        List<Menu> menus = menuMapper.queryPage(menu);
        for (Menu menu1 : menus) {
            Long parentId = menu1.getParentId();
            if (parentId != null) {
                menu1.setParent(menuMapper.queryById(parentId));
            }
        }
        return new PageList<>(total, menus);
    }

    @Override
    public List<Menu> queryMenuTree() {
        List<Menu> menus = menuMapper.queryMenuTree();
        return menus;
    }

    @Override
    public Integer queryCountByParent() {
        Integer count = menuMapper.queryCountByParent();
        return count;
    }

    @Override
    public Integer queryCountByParentId(Long parentId) {
        Integer count = menuMapper.queryCountByParentId(parentId);
        return count;
    }

    @Override
    public List<Menu> queryTree() {
        // 1.查询所有数据
        List<Menu> menus = menuMapper.queryAll();
        // 转成map
        Map<Long, Menu> map = new HashMap<>();
        for (Menu menu : menus) {
            map.put(menu.getId(), menu);
        }
        // 准备一个listTree
        List<Menu> listTree = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId() == null) {
                listTree.add(menu);
            } else {
                Menu parent = map.get(menu.getParentId());
                if (parent != null) {
                    parent.getChildren().add(menu);
                }
            }
        }
        return listTree;
    }

    @Override
    public List<Long> queryMenusView(Long id) {
        List<Long> ids = menuMapper.queryMenusView(id);
        return ids;
    }

    @Override
    public List<Menu> queryByUserId(Long id) {
        return menuMapper.queryByUserId(id);
    }

    @Override
    public void add(Menu menu) {
        Menu parent = menu.getParent();
        if (parent != null) {
            menu.setParentId(parent.getId());
        }
        menuMapper.add(menu);
    }

    @Override
    public void update(Menu menu) {
        Menu parent = menu.getParent();
        if (parent != null) {
            menu.setParentId(parent.getId());
        }
        menuMapper.update(menu);
    }
}
